/*
 * Peralta Santa Anna Victor Miguel
 * Diciembre 2011
 * Stored Procedure:
 *
 * Sacamos la diferencia en fechas
 */

CREATE FUNCTION DATEdiff 
	(
		diffType VARCHAR, 
		DATE1 DATE, 
		DATE2 DATE
		
	) RETURNS INTEGER AS $$

DECLARE

	YEAR_CONST VARCHAR := 'year';
	MONTH_CONST VARCHAR := 'month';
 
	diffInINTERVAL INTERVAL;
	diffInDoublePrecision DOUBLE PRECISION := 0;
	diffInINTEGER INTEGER := 0;
	DATETemp DATE;

BEGIN
 
	diffInINTERVAL := age(DATE2, DATE1);
 
	IF lower($1) = lower(YEAR_CONST) THEN
		diffInDoublePrecision := DATE_part('Year', diffInINTERVAL);
	ELSEIF lower($1) = lower(MONTH_CONST) THEN
		diffInDoublePrecision := (DATE_part('Year', diffInINTERVAL) * 12) + DATE_part('Month', diffInINTERVAL);
	END IF;
 
	diffInINTEGER := CAST(diffInDoublePrecision AS INTEGER);
	RETURN diffInINTEGER;
END;
$$ LANGUAGE plpgsql;

--select * from datediff('year','2011/01/01',now()::date);

